package com.faxsun.web.aspect;

import java.util.Calendar;

import javax.servlet.http.HttpSession;

import mtons.modules.pojos.UserContextHolder;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.faxsun.core.persist.entity.LiveInteractionPO;
import com.faxsun.core.service.LiveInteractionService;
import com.faxsun.web.pojos.FSUserProfile;
import com.faxsun.web.utils.HttpContextHelper;

@Aspect
@Component
public class InterationAspect {
	private static final Logger logger = LoggerFactory
			.getLogger(InterationAspect.class);
	@Autowired
	LiveInteractionService liveInteractionService;

	@Pointcut("execution(public * com.faxsun.web.controller.news.LiveController.broadcast(..)) "
			+ "||execution(public * com.faxsun.web.endpoint.LiveCommentEndpoint.getRecentComments(..))"
			+ "||execution(public * com.faxsun.web.endpoint.live.LiveMsgEndpoint.list*(..))"
			+ "||execution(public * mblog.web.controller.front.comment.CommentController.post(..))")
	void pointCut() {

	}

	@Around(value = "pointCut()")
	public Object recordUserInteraction(ProceedingJoinPoint pcj) {
		FSUserProfile up = (FSUserProfile) UserContextHolder.getUserProfile();
		if (up == null) {
			try {
				return pcj.proceed();
			} catch (Throwable e) {
				logger.warn("User not login,proceed to next method!Error message:"
						+ e.getMessage());
			}
		}
		HttpSession session = HttpContextHelper.getSession();
		try {
			MethodSignature sig = (MethodSignature) pcj.getSignature();
			String methodName = sig.getName();
			logger.debug("Aspect is processing:" + sig.getName());
			long liveId = 0;
			if (methodName.matches("broadcast")) {
				liveId = (long) pcj.getArgs()[0];// Long.parseLong(pcj.getArgs()[0].toString());
			} else if (methodName.matches("getRecentComments")) {
				liveId = (long) pcj.getArgs()[2];
			} else if (methodName.contains("list")) {
				liveId = (long) pcj.getArgs()[1];
			} else if (methodName.matches("post")) {
				liveId = (long) pcj.getArgs()[0];
			}
			if (liveId == 0) {
				logger.error(String.format(
						"Exception happened when process method:[%s]",
						methodName));
			} else {
				LiveInteractionPO lpo = new LiveInteractionPO();
				lpo.setLiveId(liveId);
				lpo.setUserId(up.getId());
				lpo.setSessionId(session.getId());
				lpo.setUpdateTime(Calendar.getInstance().getTime());
				this.liveInteractionService.saveOrUpdateStats(lpo);
			}
			return pcj.proceed();
		} catch (Throwable e) {
			logger.error("", e);
			try {
				return pcj.proceed();
			} catch (Throwable e1) {
				logger.error("", e);
			}
		}
		return null;
	}
}
